<template>
  <c-form :inline="true" :form="form" ref="refForm"></c-form>
  <el-dialog
    title="设置字段"
    v-model="visible"
    width="800px"
    append-to-body
    destroy-on-close
  >
    <c-class-fields-choose
      :businessObj="businessObj"
      ref="fieldsRef"
    ></c-class-fields-choose>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submitFields">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import ClassFieldsChoose from "./ClassFieldsChoose";
import Form from "@/components/Form";
import { serviceTaskForm } from "@/components/bpmn/components/bpmnPropertiesPanel/forms";
import { getServiceExecuteList } from "@/api/bpmnApi";

export default {
  name: "ServiceTaskClassField",
  components: {
    "c-form": Form,
    "c-class-fields-choose": ClassFieldsChoose,
  },
  props: {
    businessObj: {
      type: Object,
    },
    modeler: {
      type: Object,
    },
  },
  data() {
    return {
      visible: false,
      form: serviceTaskForm.call(this),
    };
  },
  methods: {
    fieldsDialogDataReset() {
      this.visible = true;
    },

    // 保存设置字段
    async submitFields() {
      const fieldsData = this.$refs.fieldsRef.fieldsData;
      const validate = this.validateFieldsData(fieldsData);
      if (!validate) return;
      const formatFieldsData = fieldsData.map((item) => ({
        elementName: "activiti:Field",
        properties: {
          name: item.fieldName,
          [item.fieldType]: item.fieldValue,
        },
      }));
      this.modeler.createExtensionElements(formatFieldsData);
      this.visible = false;
      const length = fieldsData.length;
      this.form.items.fields.options =
        length > 0 ? [{ key: 1, label: length + "字段" }] : [];
    },

    // 校验
    validateFieldsData(data) {
      for (let i = 0, l = data.length; i < l; i++) {
        if (
          data[i].fieldName === "" ||
          data[i].fieldType === "" ||
          data[i].fieldValue === ""
        ) {
          this.$message.error("字段信息不完整，请完善");
          return false;
        }
      }
      return true;
    },
  },
  async mounted() {
    const rst = await getServiceExecuteList({});
    if (!rst?.success) {
      this.$message({
        type: "warning",
        message: rst.message,
      });
    }
    this.form.items.class.options = rst.data.map((item) => ({
      value: item.executeClass,
      label: item.executeName,
    }));
    this.form.models.class = this.modeler.getProperty("class");
    const length = this.businessObj?.extensionElements?.values?.length || 0;
    this.form.items.fields.options =
      length > 0 ? [{ key: 1, label: length + "字段" }] : [];
  },
};
</script>